package controller

import (
	"database/sql"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/jmoiron/sqlx"
	"strconv"
	"vip_video/configx"
	"vip_video/internal/library"
	"vip_video/internal/logic"
	"vip_video/models"
	"vip_video/types"
)

type VideoController struct {
	Db     *sqlx.DB
	Config *configx.Config
}

func NewVideoController() *VideoController {
	return &VideoController{}
}

func (vc *VideoController) WithDb(db *sqlx.DB) *VideoController {
	vc.Db = db
	return vc
}

func (vc *VideoController) WithConfig(config *configx.Config) *VideoController {
	vc.Config = config
	return vc
}

func (vc *VideoController) Index(ctx *gin.Context) {
	response := library.NewResponse(ctx)
	db := library.NewDbLibrary(ctx, vc.Db).Table("fa_video").WithOrderBy("view_num", "desc")
	if categoryId, ok := ctx.GetQuery("category_id"); ok {
		db = db.WhereEq("category_id", categoryId)
	}
	if title, ok := ctx.GetQuery("title"); ok {
		db = db.WhereLike("title", "%"+title+"%")
	}
	var list = make([]*models.VideoModel, 0)
	if err := db.Page(&list); err != nil {
		response.Error(err.Error())
		return
	}
	for _, item := range list {
		item = item.GetFullThumbAttr()
	}
	response.Success("", db.BuildPageData(list))
}

func (vc *VideoController) Detail(ctx *gin.Context) {
	id := ctx.Param("id")
	response := library.NewResponse(ctx)
	var detail models.VideoModel
	err := vc.Db.Get(&detail, "select v.*,vc.title as category_name from fa_video v left join fa_video_category vc on v.category_id=vc.id where v.id = ? limit 1;", id)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			response.Error("视频不存在")
			return
		}
		response.Error(err.Error())
		return
	}
	detail = *detail.GetFullThumbAttr()
	response.Success("", detail)
}

func (vc *VideoController) Channel(ctx *gin.Context) {
	id := ctx.Param("id")
	response := library.NewResponse(ctx)
	var list = make([]*models.VideoChannelModel, 0)
	if err := vc.Db.Select(&list, "select * from fa_video_channel where video_id=?;", id); err != nil {
		response.Error(err.Error())
		return
	}
	response.Success("", list)
}

func (vc *VideoController) Chapter(ctx *gin.Context) {
	videoId := ctx.Param("video_id")
	channelId := ctx.Param("channel_id")
	response := library.NewResponse(ctx)
	var list = make([]*models.VideoChapterModel, 0)
	if err := vc.Db.Select(&list, "select * from fa_video_chapter where video_id=? and channel_id=?;", videoId, channelId); err != nil {
		response.Error(err.Error())
		return
	}
	for _, model := range list {
		model = model.FullThumb()
	}
	response.Success("", list)
}

func (vc *VideoController) M3u8(ctx *gin.Context) {
	response := library.NewResponse(ctx)
	chapterId, err := strconv.Atoi(ctx.Param("chapter_id"))
	if err != nil {
		response.Error("系统错误")
		return
	}
	url, err := logic.NewVideoLogic(vc.Db).WithConfig(vc.Config).M3u8(int64(chapterId))
	if err != nil {
		response.Error(err.Error())
		return
	}
	response.Success("", gin.H{
		"url": url,
	})
	return
}

func (vc *VideoController) Record(ctx *gin.Context) {
	var request types.VideoRecordRequest
	response := library.NewResponse(ctx)
	if err := ctx.ShouldBind(&request); err != nil {
		response.ErrorAbort(err.Error())
		return
	}
	auth := ctx.MustGet("auth").(*library.AuthLibrary)
	chapterId := ctx.Param("chapter_id")
	chapter, _ := strconv.Atoi(chapterId)
	if err := logic.NewVideoLogic(vc.Db).WithConfig(vc.Config).Record(auth, int64(chapter), request.Second); err != nil {
		response.Error(err.Error())
		return
	}
	response.Success("记录成功", nil)
}

func (vc *VideoController) GetRecord(ctx *gin.Context) {
	response := library.NewResponse(ctx)
	auth := ctx.MustGet("auth").(*library.AuthLibrary)
	chapterId := ctx.Param("chapter_id")
	chapter, _ := strconv.Atoi(chapterId)
	var record models.ChapterHistory
	ok := false
	var s uint32
	if err := vc.Db.Get(&record, "select * from fa_chapter_history where user_id=? and chapter_id = ?;", auth.GetUserId(), chapter); err == nil {
		ok = true
		s = record.Second
	}
	response.Success("", gin.H{
		"ok":     ok,
		"second": s,
	})
	return
}
